# tools/json_tool.py
import json
import logging

def json_encode(data: dict) -> str:
    return json.dumps(data, indent=4)

def json_decode(json_str: str) -> dict:
    try:
        return json.loads(json_str)
    except json.JSONDecodeError as e:
        logging.error(f"JSON 解码失败：{e}")
        return None

def json_format_and_validate(json_str: str) -> str:
    try:
        parsed_json = json.loads(json_str)
        formatted_json = json.dumps(parsed_json, indent=4)
        return formatted_json
    except json.JSONDecodeError as e:
        logging.error(f"JSON 格式错误：{e}")
        return f"格式错误：{e}"

def run():
    print("\n欢迎使用 JSON 工具")
    print("1. 编码")
    print("2. 解码")
    print("3. 格式化并检查 JSON")
    choice = input("请选择操作（1-3）：")
    if choice == "1":
        data = input("请输入要编码的 Python 对象（字典格式）：")
        try:
            result = json_encode(eval(data))
            print(f"编码结果：\n{result}")
        except Exception as e:
            print(f"编码失败：{e}")
    elif choice == "2":
        json_str = input("请输入要解码的 JSON 字符串：")
        result = json_decode(json_str)
        if result is not None:
            print(f"解码结果：\n{result}")
    elif choice == "3":
        json_str = input("请输入要格式化和检查的 JSON 字符串：")
        result = json_format_and_validate(json_str)
        print(f"格式化结果：\n{result}")
    else:
        print("无效选项！")